package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Employee;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.DishSetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class DishServiceImpl implements DishService {


    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private DishSetmealMapper dishSetmealMapper;
    @Override
    @Transactional
    // 同时操作多个表，使用事务管理的注解
    public void saveWithFlavor(DishDTO dishDTO) {
        log.info("新增菜品: {}", dishDTO);
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        List<DishFlavor> flavors = dishDTO.getFlavors();
        // 新增一条菜品
        dishMapper.saveDish(dish);
        // 增加了回显功能，所以可以获取id
        log.info("新增菜品的id是：{}", dish.getId());

        // 新增多条口味
        if (flavors != null && !flavors.isEmpty()){
            // 为菜品口味设置菜品id
            flavors.forEach(dishFlavor -> dishFlavor.setDishId(dish.getId()));
        }
        dishFlavorMapper.saveFlavors(flavors);
    }

    @Override
    public PageResult page(DishPageQueryDTO dishPageQueryDTO) {
//        使用PageHelper
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
//        PageHelper必须返回Page类型
        Page<DishVO> page = dishMapper.page(dishPageQueryDTO);
        long total = page.getTotal();
        List<DishVO> records = page.getResult();
        return new PageResult(total, records);
    }

    @Override
    @Transactional
    // 批量删除菜品
    public void delete(List<Long> ids) {
        // 1、判断是否在售卖状态
        for (Long id : ids) {
            Dish dish = dishMapper.getById(id);
            log.info("菜品：{}", dish);
            if (Objects.equals(dish.getStatus(), StatusConstant.ENABLE)) {
                // 在售，不能删除
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        // 2、是否包含在套餐里边
        Integer num = dishSetmealMapper.isInSetmeal(ids);
        log.info("num:{}", num);
        if (num > 0) {
            // 在套餐里边，不能删除
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        // 3、删除菜品数据
        dishMapper.delete(ids);
        // 4、删除菜品对应的口味数据
        dishFlavorMapper.deleteByDishIds(ids);
    }

    @Override
    /**
     * 起售、停售
     * @param status
     * @param ids
     */
    public void startOrStop(Integer status, Long id) {
        Dish dish = new Dish();
        dish.setId(id);
        dish.setStatus(status);

        dishMapper.startOrStop(dish);
    }

    @Override
    @Transactional
    public void updateDish(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        log.info("修改菜品：{}", dish);
        // 修改菜品
        dishMapper.updateDish(dish);
        // 给口味数据设置回显 id
        dishDTO.getFlavors().forEach(dishFlavor -> dishFlavor.setDishId(dish.getId()));
        // 删除原来的口味数据
        List<Long> ids = Collections.singletonList(dishDTO.getId());
        dishFlavorMapper.deleteByDishIds(ids);
        // 增加新的口味数据
        if (dishDTO.getFlavors() != null && !dishDTO.getFlavors().isEmpty()){
            dishFlavorMapper.saveFlavors(dishDTO.getFlavors());
        }
    }

    @Override
    @Transactional
    public DishVO getByIdWithFlavor(Long id) {
        DishVO dishVO = new DishVO();
        // 根据 id 查菜品
        Dish dish = dishMapper.getById(id);
        // 根据 id 查口味
        List<DishFlavor> flavors = dishFlavorMapper.getByDishId(id);
        // 封装成DishVO
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(flavors);
        return dishVO;
    }

    /**
     * 根据分类id查询菜品
     *
     * @param id
     * @return
     */
    @Override
    public List<DishVO> getByCategoryId(Long id) {
        // 根据分类 id 查菜品
        List<DishVO> list = dishMapper.getByCategoryId(id);
        return list;
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {

        // 根据分类 id 查菜品以及对应口味
        List<DishVO> dishVOList = dishMapper.getByCategoryId(dish.getCategoryId());
        for (DishVO dishVO : dishVOList) {
            Long dishId = dishVO.getId();
            // 根据菜品 id 查口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(dishId);
            dishVO.setFlavors(flavors);
        }
        return dishVOList;
    }
}
